package com.beesphere.products.throttling.tests;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ThreadTimeoutUnitOfWork extends TestUnitOfWork {

	private static final long serialVersionUID = -8002627944815736232L;

	private static final Logger logger = LoggerFactory.getLogger (ThreadTimeoutUnitOfWork.class);

	private static final int FOREVER = 20000;
	
	@Override
	public Object execute () throws Exception {
		Thread t = new Thread () {
			public void run () {
				try {
					blockForever();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		};
		//t.setDaemon (true);
		t.start ();
		Thread.sleep (12000);
		return "Hello World";
	}

	void blockForever() throws InterruptedException {
		// This is what makes this object toxic. Sometimes it
		// blocks forever
		// when called. (Ok... not really forever in this
		// example, but long
		// enough to see the problem.)
		try {
			for (int i = 0; i < 4; i++) {
				logger.debug ("5 more seconds");
				Thread.sleep (5000);
			}
		} catch (InterruptedException e) {
			// Bad code - ignore interruption, just keep running
			e.printStackTrace();
			Thread.sleep(FOREVER);
		}
	}
	
	@Override
	public Object getContext () {
		return null;
	}
	
}
